package service.dataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import service.exceptions.DBAlreadyRunningException;

public class DataBase {

	private final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	private static final String JDBC_URL = "jdbc:mysql://localhost/pizzeria";
	private static final String USER = "root";
	private static final String PASSWORD = "clavenueva";

	private static boolean running = false;

	private Connection connection;
	private Statement statment;
	private Query query;
	private InsertData insert;

	public DataBase() throws DBAlreadyRunningException {
		if (running == true) throw new DBAlreadyRunningException(null);
		if (connection == null) {

			try {
				Class.forName(JDBC_DRIVER);
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}

			try {
				connection = DriverManager.getConnection(JDBC_URL, USER,
						PASSWORD);
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}

		}
		try {
			statment = connection.createStatement();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		query = new Query(this);
		insert=new InsertData(this);
		running = true;
	}

	public void closeConnection() {
		if (running == true) {
			if (connection != null) {
				try {
					running=false;
					connection.close();
					connection = null;
				} catch (SQLException e) {
					throw new RuntimeException(e);
				}

			}
		}
	}

	public Statement getStatment() {
		return statment;
	}
	
	public Query runAQuery(){
		return query;
	}
	
	public InsertData insert(){
		return insert;
	}
	
	public Connection getConnection() {
		return connection;
	}

}
